<template>
  <el-card class="box-card">
    <!-- 使用类名绑定icon图标 加ele -->
    <el-button type="primary" :icon="Plus" @click="dialogShow"
      >添加品牌</el-button
    >
    <el-table
      :data="tableData"
      style="width: 100%"
      border
      class="table"
      v-loading="loading"
    >
      <el-table-column label="序号" type="index" width="60" align="center" />
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column prop="logoUrl" label="品牌LOGO">
        <!-- v-slot={row} 接收一行的数据 -->
        <template v-slot="{ row }">
          <!-- 
            lazy 图片懒加载
           -->
          <el-image :src="row.logoUrl" fit="fill" lazy class="trademark-logo">
            <!-- 具名插槽：当图片加载失败时显示的内容 -->
            <template #error>
              <div class="image-slot">
                <el-icon><icon-picture /></el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template v-slot="{ row }">
          <el-button
            type="warning"
            :icon="Edit"
            size="small"
            @click="editor(row)"
          ></el-button>
          <el-button
            type="danger"
            :icon="Delete"
            @click="deleteBrand(row.id)"
            size="small"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 6, 9, 12]"
      :small="small"
      :background="background"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="totalPage"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog
      v-model="dialogVisible"
      :title="formData.id ? '修改品牌' : '添加品牌'"
      :before-close="handleClose"
    >
      <el-form ref="formDom" :model="formData" :rules="formRules">
        <el-form-item label="品牌名称" prop="tmName">
          <el-input class="brandWidth" v-model="formData.tmName" />
        </el-form-item>
        <el-form-item label="品牌logo" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="BASE_URL + '/admin/product/fileUpload'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="formData.logoUrl"
              :src="formData.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitBrand"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "XBrand",
};
</script>

<script lang="ts" setup>
import {
  Plus,
  Edit,
  Delete,
  Picture as IconPicture,
} from "@element-plus/icons-vue";
import { useSettingsStore } from "../../../stores/settings";
import {
  reqBrandList,
  reqBrandListPage,
  reqAddBrand,
  reqRemoveBrand,
  reqChangeBrand,
} from "@/api/product/brand";
import type { ArrayTableObj, tableObj } from "../../../api/product/model/index";
import { onMounted, ref, reactive, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { UploadProps } from "element-plus";

// const setStore=useSettingsStore()
const currentPage = ref(1);
const pageSize = ref(3);
const totalPage = ref(0);
const small = ref(false);
const background = ref(false);
const loading = ref(false);
const tableData = ref<ArrayTableObj>([]);
function handleSizeChange(e: any) {
  requestBrandList();
}
function handleCurrentChange(pageNo: number) {
  requestBrandList();
}
async function requestBrandList() {
  loading.value = true;
  let result = await reqBrandListPage(currentPage.value, pageSize.value);
  totalPage.value = result.total;
  tableData.value = result.records;
  loading.value = false;
}
onMounted(requestBrandList);

/***********弹窗功能*****************************
 */
const BASE_URL = import.meta.env.VITE_API_URL;
const dialogVisible = ref(false);
function dialogShow() {
  tagShow();
}
function editor(row: any) {
  tagShow(row.id, row.tmName, row.logoUrl);
}
function tagShow(id = "", tmName = "", logoUrl = "") {
  formData.tmName = tmName;
  formData.logoUrl = logoUrl;
  dialogVisible.value = true;
  formData.id = id;
  nextTick(() => {
    formDom.value.clearValidate();
  });

  // formDom.value.clearValidate()
}
const formData = reactive({
  tmName: "",
  logoUrl: "",
  id: "",
});
const formDom = ref();
const formRules = reactive({
  tmName: [
    {
      // 必填项
      required: true,
      // 校验失败。提示错误信息
      message: "请输入品牌名称",
      // 触发表单校验的时机：失去焦点
      trigger: "blur",
    },
    {
      min: 2,
      max: 10,
      message: "品牌名称必须为2-10位",
      trigger: "blur",
    },
  ],
  logoUrl: [
    {
      // 必填项
      required: true,
      // 校验失败。提示错误信息
      message: "请上传图片LOGO",
    },
  ],
});
async function submitBrand() {
  if (!formData.id) {
    await formDom.value.validate();
    const { tmName, logoUrl } = formData;
    await reqAddBrand(tmName, logoUrl);
    ElMessage.success("添加品牌成功");
    dialogVisible.value = false;
    requestBrandList();
  } else {
    const { tmName, logoUrl, id } = formData;
    await reqChangeBrand(id, logoUrl, tmName);
    ElMessage.success("修改品牌成功");
    dialogVisible.value = false;
    requestBrandList();
  }
}
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  //选择图片赋值的地址
  // formData.logoUrl = URL.createObjectURL(uploadFile.raw!);
  console.log(response);
  (formData.logoUrl = response.data),
    // 清空表单校验失败的信息
    // trademarkFormRef.value.clearValidate(); // 清空所有表单项的校验信息
    formDom.value.clearValidate(["logoUrl"]); // 清空logoUrl表单项的校验信息
};

const imageRules = ["image/jpeg", "image/png"];
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (!imageRules.includes(rawFile.type)) {
    ElMessage.error("Avatar picture must be JPG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};
const handleClose = (done: () => void) => {
  ElMessageBox.confirm("Are you sure to close this dialog?")
    .then(() => {
      done();
    })
    .catch(() => {
      // catch error
    });
};
/**************************
 * 删除
 */
async function deleteBrand(b: any) {
  await reqRemoveBrand(b);
  ElMessage.success("删除品牌成功");
  requestBrandList();
}
</script>

<style scoped>
.table {
  margin-top: 20px;
}
.trademark-logo {
  width: 120px;
}
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 30px;
}
.image-slot .el-icon {
  font-size: 30px;
}
.brandWidth {
  width: 400px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader :deep(.el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
